﻿using EYangFrame.DataAccess.Global;
using EYangFramewirk.Business.MessageSystem.Interfaces;
using EYangFramework.Domain.Entitys.Entrys;
using EYangFramework.Domain.Repositorys;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EYangFramewirk.Business.MessageSystem.Implementation
{
    public class BLLMessageMain : IBLLMessageMain
    {
        private IRepository<Role> RepositoryRole { get; set; }
        private IRepository<Message> RepositoryMessage { get; set; }
        public BLLMessageMain(IRepository<Role> repositoryRole, IRepository<Message> repositoryMessage)
        {
            this.RepositoryRole = repositoryRole;
            this.RepositoryMessage = repositoryMessage;
        }
        public void Dispose()
        {
            RepositoryRole.DbContext.Dispose();
            RepositoryMessage.DbContext.Dispose();
        }

        public List<Role> GetAllRoles()
        {
            return RepositoryRole.GetAllListNoTracking(t => true);
        }

        public bool ReadMessage(List<Guid> messageGuids)
        {
            //为了要求所有的消息一定要处理,所以不支持一次处理所有的消息
            foreach (var item in messageGuids)
            {
                var message = RepositoryMessage.GetAllList(m => m.ID == item).First();
                message.ReadUser += GlobalInfo.CurrentUser.USERNAME + ",";
                message.ReadTimes += DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ",";
                RepositoryMessage.Update(message);
            }
            return true;
        }
        public bool ReadMessage(Guid messageGuids)
        {
            var message = RepositoryMessage.GetAllList(m => m.ID == messageGuids).First();
            message.ReadUser += GlobalInfo.CurrentUser.USERNAME + ",";
            message.ReadTimes += DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ",";
            RepositoryMessage.Update(message);
            return true;
        }

        public List<Message> GetAllMessages(Guid user)
        {
            string userStr = user.ToString();
            return RepositoryMessage.GetAllNoTracking().Where(t => System.Data.Entity.DbFunctions.DiffDays(DateTime.Now, t.CREATETIME) <=5  && t.To.Contains(userStr))
                .OrderByDescending(t => t.CREATETIME).ToList();//只获取最后五天的消息
        }
    }
}
